package supertuxwar;

import net.phys2d.raw.Body;
import net.phys2d.raw.CollisionEvent;
import net.phys2d.raw.StaticBody;
import net.phys2d.raw.World;
import net.phys2d.raw.shapes.Box;

import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.SpriteSheet;

public class Water extends AbstractEntity {
	
	/** The sprite sheet containing the wave sprites */
	private SpriteSheet wave;
	
	/** The width of the crate */
	private float width;
	/** The height of the crate */
	private float height;
	
	/** The current frame of animation */
	private int frame;
	/** The timer controlling frame change */
	private int frameTimer = 0;
	/** The interval between animation frame change in milliseconds */
	private int frameInterval = 150;
	
	public Water(float x, float y, float width, float height) throws SlickException {
		this.width = width;
		this.height = height;

		wave = new SpriteSheet("res/wave.png", 32, 32);
		body = new StaticBody(new Box(width,height));
		body.setPosition(x,y);
		body.setFriction(0.1f);
	}
	
	public String getName() {
		return "Water";
	}

	@Override
	public Body getBody() {
		return body;
	}

	@Override
	public void preUpdate(int delta) {
		
		frameTimer -= delta;
		while (frameTimer < 0) {
			frame++;
			frameTimer += frameInterval;
		}
	}

	@Override
	public void update(int delta) {
		if (world == null) {
			return;
		}
		
		// loop through the collision events that have occured in the
		// world
		CollisionEvent[] events = world.getContacts(body);
		
		for (int i=0;i<events.length;i++) {
			
			if(events[i].getBodyA() == body) {
				Object obj = events[i].getBodyB().getUserData();
				if(obj instanceof Actor) {
					Actor actor = (Actor)obj;
					if(!actor.death()) {
						actor.setDeath(true);
					}
				}
			} else {
				Object obj = events[i].getBodyA().getUserData();
				if(obj instanceof Actor) {
					Actor actor = (Actor)obj;
					if(!actor.death()) {
						actor.setDeath(true);
					}
				}
			}
		}
	}

	@Override
	public void render(Graphics g) {
		int f = frame % 3;
		
		for(int i=0; i<width/32; i++) {
			Image image = wave.getSprite(f%3, 0);
			image.drawCentered(16+i*32, 584);
		}
	}

}
